package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.CommonDialog.NoteOtherRightMenuDialog;
import com.mission.schedule.R;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.service.DownImageService;
import com.mission.schedule.utils.CalendarChange;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.ListViewForScrollView;
import com.mission.schedule.utils.MyLinearLayout;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


@SuppressLint({"SimpleDateFormat", "HandlerLeak"})
public class QDYLActivity extends BaseActivity implements OnClickListener {


    @ViewResId(id = R.id.top_ll_back)
    private LinearLayout back;
    @ViewResId(id = R.id.my_friend_ll_right)
    private RelativeLayout my_friend_ll_right;
    @ViewResId(id = R.id.title)
    private TextView title_tv;
    @ViewResId(id = R.id.username)
    private TextView username;
    @ViewResId(id = R.id.header_image)
    private ImageView header_image;
    @ViewResId(id = R.id.number)
    private TextView number;
    @ViewResId(id = R.id.zan_num)
    private TextView zan_num;
    @ViewResId(id = R.id.zan)
    private TextView zan;
    @ViewResId(id = R.id.listview)
    private ListViewForScrollView listview;
    @ViewResId(id = R.id.scrollview)
    private ScrollView scrollview;

    Context context;

    SharedPrefUtil sharedPrefUtil = null;

    String title;
    String titleId;
    String path;
    String time;
    String name;
    String rednum;
    String goodnum = "0";
    String num;
    String userid;
    String uid;

    boolean isGood = false;

    ListAdapter listAdapter;
    int stylee = 0;

    @Override
    protected void setListener() {
        back.setOnClickListener(this);
        zan.setOnClickListener(this);
        my_friend_ll_right.setOnClickListener(this);
    }


    @Override
    protected void setContentView() {
        setContentView(R.layout.dx_detail_activity);
        title = getIntent().getStringExtra("title");
        titleId = getIntent().getStringExtra("titleId");
        path = getIntent().getStringExtra("path");
        time = getIntent().getStringExtra("time");
        name = getIntent().getStringExtra("name");
        rednum = getIntent().getStringExtra("redNum");
        goodnum = getIntent().getStringExtra("goodNum");
        num = getIntent().getStringExtra("num");
        uid = getIntent().getStringExtra("uid");
        stylee = getIntent().getIntExtra("stylee", 0);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
//        my_friend_ll_right.setVisibility(View.GONE);
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);

        userid = sharedPrefUtil.getString(this, ShareFile.USERFILE, ShareFile.USERID, "");

//        queryISGood();
        if (title.isEmpty()){
            title_tv.setVisibility(View.GONE);
        } else {
            title_tv.setText(title);
        }
        number.setText("浏览" + StringUtils.getIsStringEqulesNull(rednum) + "次");
        zan_num.setText(StringUtils.getIsStringEqulesNull(goodnum) + "人");
        username.setText("@" + name + " " + time.substring(5, time.length() - 3).replace('T', ' '));

        if (path.isEmpty()) {
            header_image.setVisibility(View.GONE);
        } else {
            header_image.setVisibility(View.VISIBLE);
            String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
            File outfile = new File(dicr, "TimeApp");
            // 如果文件不存在，则创建一个新文件
            if (!outfile.isDirectory()) {
                try {
                    outfile.mkdir();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            Bitmap bitmap = BitmapFactory.decodeFile(outfile + "/" + path.replace('/', '0'));

            if (bitmap == null) {
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showStubImage(R.mipmap.loads)          // 设置图片下载期间显示的图片
                        .showImageForEmptyUri(R.mipmap.loads)  // 设置图片Uri为空或是错误的时候显示的图片
                        .showImageOnFail(R.mipmap.loads)       // 设置图片加载或解码过程中发生错误显示的图片
                        .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                        .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                        .build();
                String imageUrl = URLConstants.图片 + path + "&imageType=15&imageSizeType=1";
                ImageLoader.getInstance().displayImage(imageUrl, header_image, options);
                Intent intent = new Intent(context, DownImageService.class);
                intent.setAction("downimage");
                intent.putExtra("url", imageUrl);
                intent.putExtra("name", path.replace('/', '0'));
                startService(intent);
            } else {
                header_image.setImageBitmap(bitmap);
            }
        }

        String rizhi = sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, "");
        String[] ri = rizhi.split(",");
        if (ri.length > 0) {
            for (String item : ri) {
                if (item.equals(titleId)) {
                    zan.setTextColor(getResources().getColor(R.color.gongkai_txt));
                    zan.setBackground(getResources().getDrawable(R.drawable.zan_y_gray));
                    isGood = true;
                    break;
                }
            }
        }

        getdata();
    }


    @Override
    protected void setAdapter() {
        listAdapter = new ListAdapter(listBeanList);
        listview.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
        scrollview.post(new Runnable() {
            @Override
            public void run() {
                scrollview.scrollTo(0,0);
            }
        });
        title_tv.setFocusable(true);
        title_tv.setFocusableInTouchMode(true);
        title_tv.requestFocus();

    }

    ProgressUtil progressUtil = new ProgressUtil();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.top_ll_back:
                onBackPressed();
                break;
            case R.id.my_friend_ll_right:
                NoteOtherRightMenuDialog noteOtherRightMenuDialog = new NoteOtherRightMenuDialog(context, R.style.dialog_translucent, getWindowManager(),true);
                noteOtherRightMenuDialog.show();
                noteOtherRightMenuDialog.setCallBack(new NoteOtherRightMenuDialog.CallBack() {
                    @Override
                    public void daiban() {
                        try {
                            App.getDBcApplication().insertScheduleData(title.isEmpty() ? title1 : title, DateUtil.formatDate(new Date()),
                                    DateUtil.formatDateTimeHm(new Date()), 1,
                                    0, 0, 1, 0,
                                    0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                    titleId, DateUtil.formatDateTimeSs(new Date()), 0, "", DateUtil.formatDateTime(new Date()),
                                    1, 0, 0, "完成任务", "g_88", name, 0, 0, 0, "",
                                    "", 0, 0, Integer.valueOf(userid),0,"","0","0");
                            App.getDBcApplication().saveCalenderNoteData(titleId, nums());
                            QueryAlarmData.writeAlarm(context.getApplicationContext());
                            Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                            Bundle extras = new Bundle();
                            intentappwidget.putExtras(extras);
                            sendBroadcast(intentappwidget);
                            Intent intent1 = new Intent(Const.SHUAXINDATA);
                            intent1.putExtra("data", "success");
                            intent1.putExtra("index", 1);
                            intent1.putExtra("what", 2);
                            context.sendBroadcast(intent1);

                            Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();

                            StringRequest request1 = new StringRequest(Request.Method.POST, URLConstants.清单留言加入清单到日程时候调用, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                }


                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {

                                }
                            }) {
                                @Override
                                protected Map<String, String> getParams() throws AuthFailureError {
                                    Map<String, String> map = new HashMap<String, String>();
                                    map.put("titleId", titleId);
                                    map.put("uId", uid);
                                    map.put("cuId", userid);
                                    return map;
                                }
                            };
                            request1.setTag("sendsc");
                            request1.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 1.0f));
                            App.getHttpQueues().add(request1);

                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void richeng() {
                        initRiliDiaLog(title.isEmpty() ? title1 : title);
                    }

                    @Override
                    public void sendnote() {
                        if (sharedPrefUtil.getString(getApplication(),
                                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                            Intent zhuanfa = new Intent(context, NewFriendsActivity.class);
                            zhuanfa.putExtra("type", 2);
                            zhuanfa.putExtra("titleid", titleId);
                            zhuanfa.putExtra("title_userid", uid);
                            zhuanfa.putExtra("title", title.isEmpty() ? title1 : title);
                            zhuanfa.putExtra("titleimg", path);
                            zhuanfa.putExtra("noteusername", name);
                            startActivity(zhuanfa);
                        } else {
                            Toast.makeText(context, "请注册!", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void longimage() {
                        Intent intent1;
                        Bundle bundle = new Bundle();

                        intent1 = new Intent(context, QDLongImageSaveActivity.class);
                        bundle.putSerializable("list", (Serializable) listBeanList);

                        intent1.putExtra("name", name);
                        intent1.putExtra("stylee", stylee);
                        intent1.putExtra("title", title);
                        intent1.putExtras(bundle);
                        startActivity(intent1);
                    }

                    @Override
                    public void savemyqd() {

                    }
                });
                break;
            case R.id.zan:
                if (!isGood) {
                    good();
                }
                break;
            default:
                break;
        }
    }

    public String nums() {
        int tick1 = 0;
        int tick2 = 0;
        for (NoteTitleDetailBean.ListBean listBean : listBeanList) {
            if (listBean.endstate == 1) {
                tick1 += 1;
            }
            if (listBean.endstate == 2) {
                tick2 += 1;
            }
        }
        String title_new;
        if (stylee == 0) {
            if (listBeanList.size() == 0) {
                title_new = "0";
            } else {
                title_new = tick1 + "/" + listBeanList.size();
            }
        } else if (stylee == 4) {
            if (listBeanList.size() == 0) {
                title_new = "0";
            } else {
                title_new = tick1 + "/" + tick2 + "/" + listBeanList.size();
            }
        } else {
            title_new = listBeanList.size() + "";
        }

        return title_new;
    }

    /**
     * 最新清单右滑对话框
     */
    private void alterNewDialog() {
        final Dialog dialog = new Dialog(QDYLActivity.this, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(QDYLActivity.this);
        View more_pop_menu = fac.inflate(R.layout.dialog_qdfx_detail_right, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        more_pop_menu.findViewById(R.id.share_f).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                showShare();
            }
        });
        more_pop_menu.findViewById(R.id.share_p).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                showShare();
            }
        });
        more_pop_menu.findViewById(R.id.share_c).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent1 = new Intent(context, QDLongImageSaveActivity1.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("list", (Serializable) listBeanList);
                intent1.putExtra("name", name);
                intent1.putExtra("stylee", stylee);
                intent1.putExtra("title", title);
                intent1.putExtras(bundle);
                startActivity(intent1);
            }
        });
    }


    //分享其他
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        oks.setText(listBeanList.get(0).contents);

        String url = "http://www.keytimeapp.com/qingdan/qdlist-user.html?uId=" + userid + "&titleId=" + listBeanList.get(0).titleId + "&title=" + title + "&name=" + sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERNAME, "") + "&number=" + listBeanList.get(0).nums + "&from=singlemessage&isappinstalled=1&type=1";
        oks.setUrl(url);
        oks.setImageUrl(URLConstants.图片 + sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "") + "&imageType=2&imageSizeType=3");
        oks.setCallback(new newOneCallBack());
        // 启动分享GUI
        oks.show(this);
    }

    class newOneCallBack implements PlatformActionListener {

        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
        }

        @Override
        public void onCancel(Platform platform, int i) {
        }
    }


    private void queryISGood() {
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("num", num);
        params.addBodyParameter("uId", userid);
        httpUtils.send(HttpMethod.POST, URLConstants.清单发现详情是否已赞, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    QDFXGLListActivity.updateQDFXBean bean = gson.fromJson(responseInfo.result, QDFXGLListActivity.updateQDFXBean.class);
                    if (bean.status == 0) {
                        zan.setTextColor(getResources().getColor(R.color.gongkai_txt));
                        zan.setBackground(getResources().getDrawable(R.drawable.zan_y_gray));
                        isGood = true;
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    private void good() {
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("titleId", titleId);
        params.addBodyParameter("type", "0");


        params.addBodyParameter("uId", userid);

        httpUtils.send(HttpMethod.POST, URLConstants.清单公告点赞, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    QDFXGLListActivity.updateQDFXBean bean = gson.fromJson(responseInfo.result, QDFXGLListActivity.updateQDFXBean.class);
                    if (bean.status == 0) {
                        zan.setTextColor(getResources().getColor(R.color.gongkai_txt));
                        zan.setBackground(getResources().getDrawable(R.drawable.zan_y_gray));
                        zan_num.setText((Integer.valueOf(goodnum) + 1) + "人");
                        isGood = true;
                        String rizhi = sharedPrefUtil.getString(context,
                                ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, "");
                        sharedPrefUtil.putString(context,
                                ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, rizhi + "," + titleId);

                    }

                    if (bean.status == 4) {
                        Toast.makeText(QDYLActivity.this, "已点过赞", Toast.LENGTH_SHORT).show();
                        zan.setTextColor(getResources().getColor(R.color.gongkai_txt));
                        zan.setBackground(getResources().getDrawable(R.drawable.zan_y_gray));
                        zan_num.setText((Integer.valueOf(goodnum) + 1) + "人");
                        isGood = true;
                    }
                } else {
                    Toast.makeText(QDYLActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(QDYLActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }

    List<NoteTitleDetailBean.ListBean> listBeanList = new ArrayList<>();

    private void getdata() {
        listBeanList = App.getDBcApplication().getTitleNoteDetailData(userid, titleId, false);
        setAdapter();

        HttpUtils httpUtils0 = new HttpUtils(10000);
        RequestParams params0 = new RequestParams();
        params0.addBodyParameter("titleId", titleId);
        params0.addBodyParameter("type", "1");
        params0.addBodyParameter("uId", uid);
        httpUtils0.send(HttpMethod.POST, URLConstants.清单公告点赞, params0, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

        HttpUtils httpUtils1 = new HttpUtils(10000);
        RequestParams params1 = new RequestParams();
        params1.addBodyParameter("titleId", titleId);
        params1.addBodyParameter("uId", uid);
        httpUtils1.send(HttpMethod.POST, URLConstants.清单公告下载数量, params1, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    QDFXDetailActivity.GONGGAODOWNBEAN bean = gson.fromJson(responseInfo.result, QDFXDetailActivity.GONGGAODOWNBEAN.class);
                    if (bean.status == 0) {
                        lis.clear();
                        lis = bean.list;
                        if (lis.size() > 0){
                            zan_num.setText(lis.get(0).goodNum+"人");
                            goodnum = lis.get(0).goodNum+"";
                            number.setText("浏览"+lis.get(0).redNum+"次");
                            rednum = lis.get(0).redNum+"";
                        }
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }
    List<QDFXDetailActivity.GONGGAODOWNBEAN.ListBean> lis = new ArrayList<>();

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    boolean istitle1 = false;
    String title1 = "";
    class ListAdapter extends BaseAdapter {

        List<NoteTitleDetailBean.ListBean> list;

        public ListAdapter(List<NoteTitleDetailBean.ListBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(QDYLActivity.this).inflate(R.layout.qdfx_de_list_item, parent, false);

                holder.content_tv = (TextView) convertView.findViewById(R.id.content_tv);
                holder.xh = (TextView) convertView.findViewById(R.id.xh);
                holder.dd = (ImageView) convertView.findViewById(R.id.dd);
                holder.ch = (ImageView) convertView.findViewById(R.id.ch);
                holder.ll = (RelativeLayout) convertView.findViewById(R.id.ll);
                holder.santai = (ImageView) convertView.findViewById(R.id.santai);
                holder.emty_v = convertView.findViewById(R.id.emty_v);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }


            if (list.size() > 0) {
                if (!istitle1) {
                    if (!list.get(position).contents.isEmpty()) {
                        title1 = list.get(position).contents;
                        istitle1 = true;
                    }
                }
                if (stylee == 0) {
                    holder.ll.setVisibility(View.VISIBLE);
                    holder.ch.setVisibility(View.VISIBLE);
                    if (list.get(position).endstate == 0) {
                        holder.ch.setBackground(getResources().getDrawable(R.mipmap.btn_qd_unfinish_c));
                    } else {
                        holder.ch.setBackground(getResources().getDrawable(R.mipmap.btn_qd_finish_c));
                    }
                    holder.dd.setVisibility(View.GONE);
                    holder.xh.setVisibility(View.GONE);
                    holder.santai.setVisibility(View.GONE);
                } else if (stylee == 1) {
                    holder.ll.setVisibility(View.VISIBLE);
                    holder.ch.setVisibility(View.GONE);
                    holder.dd.setVisibility(View.VISIBLE);
                    holder.xh.setVisibility(View.GONE);
                    holder.santai.setVisibility(View.GONE);
                } else if (stylee == 2) {
                    holder.ll.setVisibility(View.VISIBLE);
                    holder.ch.setVisibility(View.GONE);
                    holder.dd.setVisibility(View.GONE);
                    holder.xh.setVisibility(View.VISIBLE);
                    holder.santai.setVisibility(View.GONE);
                } else if (stylee == 3) {
                    holder.ch.setVisibility(View.GONE);
                    holder.dd.setVisibility(View.GONE);
                    holder.xh.setVisibility(View.GONE);
                    holder.ll.setVisibility(View.GONE);
                    holder.santai.setVisibility(View.GONE);
                    holder.emty_v.setVisibility(View.VISIBLE);
                } else if (stylee == 4) {
                    holder.ch.setVisibility(View.GONE);
                    holder.dd.setVisibility(View.GONE);
                    holder.xh.setVisibility(View.GONE);
                    holder.ll.setVisibility(View.VISIBLE);
                    holder.santai.setVisibility(View.VISIBLE);
                    if (list.get(position).endstate == 0) {
                        holder.santai.setBackground(getResources().getDrawable(R.mipmap.icon_santai1));
                    } else if (list.get(position).endstate == 1) {
                        holder.santai.setBackground(getResources().getDrawable(R.mipmap.icon_santai2));
                    } else {
                        holder.santai.setBackground(getResources().getDrawable(R.mipmap.icon_santai3));
                    }
                }
                setcolor(list.get(position).contents, holder.content_tv);
                holder.xh.setText((position + 1) + ".");
            }


            return convertView;
        }


        class ViewHolder {
            TextView xh, content_tv;
            ImageView ch, dd, santai;
            RelativeLayout ll;
            View emty_v;
        }


    }


    //设置双#号包裹的文字颜色
    private void setcolor(String content, TextView editText) {
        if (content.length() > 1) {
            SpannableStringBuilder builder = new SpannableStringBuilder(content);
            List<Integer> integerList = new ArrayList<>();
            int index = 0;
            int count = hit(content, "#");
            if (count > 1) {
                if (count % 2 == 0) {
                    for (int i = 0; i < count; i++) {
                        if (i == 0) {
                            index = content.indexOf("#");
                        } else {
                            index = content.indexOf("#", index + 1);
                        }
                        integerList.add(index);
                    }
                    for (int i = 0; i < integerList.size(); i++) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#df7926"));
                                builder.setSpan(span, integerList.get(i - 1), integerList.get(i) + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                        }
                    }
                    editText.setText(builder);
                } else {
                    for (int i = 0; i < count - 1; i++) {
                        if (i == 0) {
                            index = content.indexOf("#");
                        } else {
                            index = content.indexOf("#", index + 1);
                        }
                        integerList.add(index);

                    }
                    for (int i = 0; i < integerList.size(); i++) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#df7926"));
                                builder.setSpan(span, integerList.get(i - 1), integerList.get(i) + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            }
                        }
                    }
                    editText.setText(builder);
                }
            } else {
                editText.setText(content);
            }
        } else {
            editText.setText(content);
        }
        editText.setLineSpacing(20, 1.0f);
    }

    /**
     * @param a 被匹配的长字符串
     * @param b 匹配的短字符串
     * @return 匹配次数
     */
    public int hit(String a, String b) {
        if (a.length() < b.length()) {
            return 0;
        }
        char[] a_t = a.toCharArray();
        int count = 0;

        for (int i = 0; i < a.length(); i++) {
            StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < b.length(); j++) {
                buffer.append(a_t[i + j]);
            }
            if (buffer.toString().equals(b)) {
                count++;
            }
        }

        return count;
    }


    public class QDBean {

        /**
         * status : 0
         * downTime : 2017-06-02T10:14:53
         * message : 成功
         * list : [{"ltype":1,"orderId":0,"states":2,"style":3,"remark1":null,"uname":"清流暖人心","cpath":"","remark2":null,"goodNum":5,"shareUrl":null,"contents":"七个戒烟方法","remark3":null,"isTop":0,"id":4504,"redNum":111,"remark4":null,"uid":260975,"num":"20170523172148548492","endstate":null,"imgUrl":"","remark5":null,"titleId":"20170523172045176901","titles":"七个戒烟方法","changeTime":"2017-05-25T11:47:32","remark6":null,"remark":"1","createTime":"2017-05-23T17:21:48","curl":"","imgPath":""}]
         * tDelList : null
         * delList : null
         */

        public int status;
        public String downTime;
        public String message;
        public Object tDelList;
        public Object delList;
        public List<ListBean> list;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public Object getTDelList() {
            return tDelList;
        }

        public void setTDelList(Object tDelList) {
            this.tDelList = tDelList;
        }

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean implements Serializable {
            /**
             * ltype : 1
             * orderId : 0
             * states : 2
             * style : 3
             * remark1 : null
             * uname : 清流暖人心
             * cpath :
             * remark2 : null
             * goodNum : 5
             * shareUrl : null
             * contents : 七个戒烟方法
             * remark3 : null
             * isTop : 0
             * id : 4504
             * redNum : 111
             * remark4 : null
             * uid : 260975
             * num : 20170523172148548492
             * endstate : null
             * imgUrl :
             * remark5 : null
             * titleId : 20170523172045176901
             * titles : 七个戒烟方法
             * changeTime : 2017-05-25T11:47:32
             * remark6 : null
             * remark : 1
             * createTime : 2017-05-23T17:21:48
             * curl :
             * imgPath :
             */

            public int ltype;
            public int orderId;
            public int states;
            public int style;
            public Object remark1;
            public String uname;
            public String cpath;
            public Object remark2;
            public int goodNum;
            public Object shareUrl;
            public String contents;
            public Object remark3;
            public int isTop;
            public int id;
            public int redNum;
            public Object remark4;
            public int uid;
            public String num;
            public Object endstate;
            public String imgUrl;
            public Object remark5;
            public String titleId;
            public String titles;
            public String changeTime;
            public Object remark6;
            public String remark;
            public String createTime;
            public String curl;
            public String imgPath;

            public int getLtype() {
                return ltype;
            }

            public void setLtype(int ltype) {
                this.ltype = ltype;
            }

            public int getOrderId() {
                return orderId;
            }

            public void setOrderId(int orderId) {
                this.orderId = orderId;
            }

            public int getStates() {
                return states;
            }

            public void setStates(int states) {
                this.states = states;
            }

            public int getStyle() {
                return style;
            }

            public void setStyle(int style) {
                this.style = style;
            }

            public Object getRemark1() {
                return remark1;
            }

            public void setRemark1(Object remark1) {
                this.remark1 = remark1;
            }

            public String getUname() {
                return uname;
            }

            public void setUname(String uname) {
                this.uname = uname;
            }

            public String getCpath() {
                return cpath;
            }

            public void setCpath(String cpath) {
                this.cpath = cpath;
            }

            public Object getRemark2() {
                return remark2;
            }

            public void setRemark2(Object remark2) {
                this.remark2 = remark2;
            }

            public int getGoodNum() {
                return goodNum;
            }

            public void setGoodNum(int goodNum) {
                this.goodNum = goodNum;
            }

            public Object getShareUrl() {
                return shareUrl;
            }

            public void setShareUrl(Object shareUrl) {
                this.shareUrl = shareUrl;
            }

            public String getContents() {
                return contents;
            }

            public void setContents(String contents) {
                this.contents = contents;
            }

            public Object getRemark3() {
                return remark3;
            }

            public void setRemark3(Object remark3) {
                this.remark3 = remark3;
            }

            public int getIsTop() {
                return isTop;
            }

            public void setIsTop(int isTop) {
                this.isTop = isTop;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getRedNum() {
                return redNum;
            }

            public void setRedNum(int redNum) {
                this.redNum = redNum;
            }

            public Object getRemark4() {
                return remark4;
            }

            public void setRemark4(Object remark4) {
                this.remark4 = remark4;
            }

            public int getUid() {
                return uid;
            }

            public void setUid(int uid) {
                this.uid = uid;
            }

            public String getNum() {
                return num;
            }

            public void setNum(String num) {
                this.num = num;
            }

            public Object getEndstate() {
                return endstate;
            }

            public void setEndstate(Object endstate) {
                this.endstate = endstate;
            }

            public String getImgUrl() {
                return imgUrl;
            }

            public void setImgUrl(String imgUrl) {
                this.imgUrl = imgUrl;
            }

            public Object getRemark5() {
                return remark5;
            }

            public void setRemark5(Object remark5) {
                this.remark5 = remark5;
            }

            public String getTitleId() {
                return titleId;
            }

            public void setTitleId(String titleId) {
                this.titleId = titleId;
            }

            public String getTitles() {
                return titles;
            }

            public void setTitles(String titles) {
                this.titles = titles;
            }

            public String getChangeTime() {
                return changeTime;
            }

            public void setChangeTime(String changeTime) {
                this.changeTime = changeTime;
            }

            public Object getRemark6() {
                return remark6;
            }

            public void setRemark6(Object remark6) {
                this.remark6 = remark6;
            }

            public String getRemark() {
                return remark;
            }

            public void setRemark(String remark) {
                this.remark = remark;
            }

            public String getCreateTime() {
                return createTime;
            }

            public void setCreateTime(String createTime) {
                this.createTime = createTime;
            }

            public String getCurl() {
                return curl;
            }

            public void setCurl(String curl) {
                this.curl = curl;
            }

            public String getImgPath() {
                return imgPath;
            }

            public void setImgPath(String imgPath) {
                this.imgPath = imgPath;
            }
        }
    }

    int[] solartime = new int[25];
    boolean isLeap = false;
    boolean isRed = false;
    ArrayList<HashMap<String, String>> data;
    String today;
    int temp_day;
    int temp_month;
    int temp_year;

    int to_day;
    int to_month;
    int to_year;
    int standard_day;
    int standard_month;
    int standard_year;
    String holiday = "";
    String curDate = "";

    int sourse;//
    String dateTime = "";// 日期
    private TextView titleTV;

    MyLinearLayout dataLinear;
    Handler handlerrili;
    LinearLayout.LayoutParams mLayoutParamss = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    private void initRiliDiaLog(final String content) {
        final Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_calender_rili, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        curDate = dateTime;

        dataLinear = (MyLinearLayout) more_pop_menu.findViewById(R.id.datalinear);
        titleTV = (TextView) more_pop_menu.findViewById(R.id.title);
        dataLinear.setBackgroundColor(Color.WHITE);
        more_pop_menu.findViewById(R.id.today).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                curDate = DateUtil.formatDate(new Date());// new Date()为获取当前系统时间
                GenData(true, curDate);
                GenView();
            }
        });
        more_pop_menu.findViewById(R.id.lastmonth).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (standard_month == 1) {
                    standard_month = 12;
                    standard_year--;
                } else {
                    standard_month--;
                }
                GenData(false, curDate);
                GenView();
                titleTV.setText(standard_year + "年" + standard_month + "月");
                dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.right_in));

            }
        });
        more_pop_menu.findViewById(R.id.nextmonth).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (standard_month == 12) {
                    standard_month = 1;
                    standard_year++;
                } else {
                    standard_month++;
                }
                GenData(false, curDate);
                GenView();
                titleTV.setText(standard_year + "年" + standard_month + "月");
                dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.left_in));

            }
        });
        handlerrili = new Handler() {
            public void handleMessage(Message msg) {
                if (msg == null) {
                    return;
                }
                switch (msg.what) {
                    case 0:
                        if (standard_month == 1) {
                            standard_month = 12;
                            standard_year--;
                        } else {
                            standard_month--;
                        }
                        GenData(false, curDate);
                        GenView();
                        titleTV.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.right_in));
                        break;

                    case 1:
                        if (standard_month == 12) {
                            standard_month = 1;
                            standard_year++;
                        } else {
                            standard_month++;
                        }
                        GenData(false, curDate);
                        GenView();
                        titleTV.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.left_in));
                        break;

                    case 2:
                        standard_year--;
                        GenData(false, curDate);
                        GenView();
                        titleTV.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.down_in));
                        break;

                    case 3:
                        standard_year++;
                        GenData(false, curDate);
                        GenView();
                        titleTV.setText(standard_year + "年" + standard_month + "月");
                        dataLinear.startAnimation(AnimationUtils.loadAnimation(context, R.anim.up_in));
                        break;

                    case 9:
                        dialog.dismiss();

                        App.getDBcApplication().insertScheduleData(content, msg.obj + "",
                                DateUtil.nowTimes(), 1,
                                0, 1, 0, 0,
                                0, 0, DateUtil.formatDateTime(new Date()), "", 0,
                                titleId, DateUtil.formatDateTimeSs(new Date()), 0, "", DateUtil.formatDateTime(new Date()),
                                1, 0, 0, "完成任务", "g_88", name, 0, 0, 0, "",
                                "", 0, 0, Integer.valueOf(userid),0,"","0","0");

                        App.getDBcApplication().saveCalenderNoteData(titleId, nums());
                        Intent intent = new Intent(Const.SHUAXINDATA);
                        intent.putExtra("data", "success");
                        intent.putExtra("index", 1);
                        intent.putExtra("what", 2);
                        context.sendBroadcast(intent);
                        QueryAlarmData.writeAlarm(context);

                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                        Bundle extras = new Bundle();
                        intentappwidget.putExtras(extras);
                        context.sendBroadcast(intentappwidget);

                        Toast.makeText(context, "添加成功", Toast.LENGTH_LONG).show();
                        break;

                    case 11:
                        Toast.makeText(context, "网络中断", Toast.LENGTH_LONG).show();
                        break;

                    case 12:
                        Toast.makeText(context, "服务器错误", Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
        dataLinear.setHandler(handlerrili);


        new LoadDataAsyncTask().execute();


    }

    class LoadDataAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
//			dialog.dismiss();
            GenData(true, curDate);
            GenView();
        }

    }

    public ArrayList<HashMap<String, String>> GenData(boolean isfirst, String date) {
        if (!date.equals("") && isfirst) {
            data = new ArrayList<HashMap<String, String>>();
            to_year = Integer.parseInt(date.split("-")[0].toString());
            to_month = Integer.parseInt(date.split("-")[1].toString());
            to_day = Integer.parseInt(date.split("-")[2].toString());
            temp_day = to_day;
            temp_month = to_month;
            temp_year = to_year;
            standard_day = to_day;
            standard_month = to_month;
            standard_year = to_year;
            today = date;
            titleTV.setText(standard_year + "年" + standard_month + "月");
        } else {
            if (isfirst) {
                data = new ArrayList<HashMap<String, String>>();
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(System.currentTimeMillis());
                to_year = c.get(Calendar.YEAR);
                to_month = c.get(Calendar.MONTH);
                to_day = c.get(Calendar.DAY_OF_MONTH);

                to_month++;
                temp_day = to_day;
                temp_month = to_month;
                temp_year = to_year;
                standard_day = to_day;
                standard_month = to_month;
                standard_year = to_year;

                today = to_year + "-"
                        + (to_month > 9 ? "" + to_month : "0" + to_month) + "-"
                        + (to_day > 9 ? "" + to_day : "0" + to_day);
                titleTV.setText(standard_year + "年" + standard_month + "月");
            } else {
                data = new ArrayList<HashMap<String, String>>();
                temp_day = standard_day;
                temp_month = standard_month;
                temp_year = standard_year;

            }
        }
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("day", temp_day + "");

        map.put("isMonth", "1"); // 1是本月
        String tempStrT = temp_year + "-"
                + (temp_month > 9 ? "" + temp_month : "0" + temp_month) + "-"
                + (temp_day > 9 ? "" + temp_day : "0" + temp_day);
        if ("".equals(StringUtils.getIsStringEqulesNull(tempStrT))) {
            tempStrT = today;
        }
        if (today.equals(tempStrT)) {
            map.put("isToday", "1"); // 1是今天
            map.put("time", today);
        } else {
            map.put("isToday", "0"); // 1是今天
            map.put("time", tempStrT);
        }
        try {
            if (CalHoliday(Integer.valueOf(temp_month
                    + (temp_day > 9 ? "" + temp_day : "0" + temp_day)))) {
                map.put("lunar", holiday);
            } else {
                map.put("lunar", CalendarChange.CalendarChange(tempStrT));
            }
            if (isRed) {
                map.put("isHoliday", "1"); // 1节日
                isRed = false;
            } else {
                map.put("isHoliday", "0"); // 1节日
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.add(map);
        for (int i = temp_day - 1; i > 0; i--) {
            String tempStr = temp_year + "-"
                    + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                    + "-" + (i > 9 ? "" + i : "0" + i);
            map = new HashMap<String, String>();
            map.put("day", i + "");
            map.put("time", tempStr);
            map.put("isToday", "0"); // 1是今天
            map.put("isMonth", "1"); // 1是本月
            try {
                if (CalHoliday(Integer.valueOf("" + temp_month
                        + (i > 9 ? "" + i : "0" + i)))) {
                    map.put("lunar", holiday);
                } else {
                    map.put("lunar", CalendarChange.CalendarChange(tempStr));
                }
                if (isRed) {
                    map.put("isHoliday", "1"); // 1节日
                    isRed = false;
                } else {
                    map.put("isHoliday", "0"); // 1节日
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.add(0, map);
        }
        int te_week = calWeek(temp_year, temp_month, 1);
        if (temp_month == 1) {
            temp_year--;
            temp_month = 12;
        } else {
            temp_month--;
        }
        calLeapYear(temp_year);
        if (temp_month == 4 || temp_month == 6 || temp_month == 9
                || temp_month == 11) {
            for (int i = 30; i > 30 - te_week; i--) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 是今天
                map.put("isMonth", "0"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(0, map);
            }
        } else if (temp_month == 2) {
            if (isLeap) {
                for (int i = 29; i > 29 - te_week; i--) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 1是今天
                    map.put("isMonth", "0"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(0, map);
                }
            } else {
                for (int i = 28; i > 28 - te_week; i--) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 1是今天
                    map.put("isMonth", "0"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(0, map);
                }
            }
        } else {
            for (int i = 31; i > 31 - te_week; i--) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 1是今天
                map.put("isMonth", "0"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(0, map);
            }
        }
        if (temp_month == 12) {
            temp_year++;
            temp_month = 1;
        } else {
            temp_month = temp_month + 1;
        }
        calLeapYear(temp_year);
        if (temp_month == 4 || temp_month == 6 || temp_month == 9
                || temp_month == 11) {
            for (int i = to_day + 1; i <= 30; i++) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 1是今天
                map.put("isMonth", "1"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(map);
            }
        } else if (temp_month == 2) {
            if (isLeap) {
                for (int i = to_day + 1; i <= 29; i++) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + i);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 是今天
                    map.put("isMonth", "1"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(map);
                }
            } else {
                for (int i = to_day + 1; i <= 28; i++) {
                    String tempStr = temp_year
                            + "-"
                            + (temp_month > 9 ? "" + temp_month : "0"
                            + temp_month) + "-"
                            + (i > 9 ? "" + i : "0" + to_day);
                    map = new HashMap<String, String>();
                    map.put("day", i + "");
                    map.put("time", tempStr);
                    map.put("isToday", "0"); // 是今天
                    map.put("isMonth", "1"); // 1是本月
                    try {
                        if (CalHoliday(Integer.valueOf("" + temp_month
                                + (i > 9 ? "" + i : "0" + i)))) {
                            map.put("lunar", holiday);
                        } else {
                            map.put("lunar",
                                    CalendarChange.CalendarChange(tempStr));
                        }
                        if (isRed) {
                            map.put("isHoliday", "1"); // 1节日
                            isRed = false;
                        } else {
                            map.put("isHoliday", "0"); // 1节日
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    data.add(map);
                }
            }
        } else {
            for (int i = to_day + 1; i <= 31; i++) {
                String tempStr = temp_year + "-"
                        + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                        + "-" + (i > 9 ? "" + i : "0" + i);
                map = new HashMap<String, String>();
                map.put("day", i + "");
                map.put("time", tempStr);
                map.put("isToday", "0"); // 是今天
                map.put("isMonth", "1"); // 1是本月
                try {
                    if (CalHoliday(Integer.valueOf("" + temp_month
                            + (i > 9 ? "" + i : "0" + i)))) {
                        map.put("lunar", holiday);
                    } else {
                        map.put("lunar", CalendarChange.CalendarChange(tempStr));
                    }
                    if (isRed) {
                        map.put("isHoliday", "1"); // 1节日
                        isRed = false;
                    } else {
                        map.put("isHoliday", "0"); // 1节日
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                data.add(map);
            }
        }
        if (temp_month >= 12) {
            temp_year++;
            temp_month = 1;
        } else {
            temp_month++;
        }
        int mm = data.size();
        for (int i = 1; i <= 42 - mm; i++) {
            String tempStr = temp_year + "-"
                    + (temp_month > 9 ? "" + temp_month : "0" + temp_month)
                    + "-" + (i > 9 ? "" + i : "0" + i);
            map = new HashMap<String, String>();
            map.put("day", i + "");
            map.put("time", tempStr);
            map.put("isToday", "0"); // 是今天
            map.put("isMonth", "0"); // 1是本月
            try {
                if (CalHoliday(Integer.valueOf("" + temp_month
                        + (i > 9 ? "" + i : "0" + i)))) {
                    map.put("lunar", holiday);
                } else {
                    map.put("lunar", CalendarChange.CalendarChange(tempStr));
                }
                if (isRed) {
                    map.put("isHoliday", "1"); // 1节日
                    isRed = false;
                } else {
                    map.put("isHoliday", "0"); // 1节日
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.add(map);
        }
        return data;
    }

    public boolean CalHoliday(int t) {
        boolean is = false;
        switch (t / 100) {
            case 2:
                if (t == solartime[0]) {
                    holiday = "立春";
                    is = true;
                } else if (t == solartime[1]) {
                    holiday = "雨水";
                    is = true;
                }
                break;
            case 3:
                if (t == solartime[2]) {
                    holiday = "惊蛰";
                    is = true;
                } else if (t == solartime[3]) {
                    holiday = "春分";
                    is = true;
                }
                break;
            case 4:
                if (t == solartime[4]) {
                    holiday = "清明";
                    is = true;
                } else if (t == solartime[5]) {
                    holiday = "谷雨";
                    is = true;
                }
                break;
            case 5:
                if (t == solartime[6]) {
                    holiday = "立夏";
                    is = true;
                } else if (t == solartime[7]) {
                    holiday = "小满";
                    is = true;
                }
                break;
            case 6:
                if (t == solartime[8]) {
                    holiday = "芒种";
                    is = true;
                } else if (t == solartime[9]) {
                    holiday = "夏至";
                    is = true;
                }
                break;
            case 7:
                if (t == solartime[10]) {
                    holiday = "小暑";
                    is = true;
                } else if (t == solartime[11]) {
                    holiday = "大暑";
                    is = true;
                }
                break;
            case 8:
                if (t == solartime[12]) {
                    holiday = "立秋";
                    is = true;
                } else if (t == solartime[13]) {
                    holiday = "处暑";
                    is = true;
                }
                break;
            case 9:
                if (t == solartime[14]) {
                    holiday = "白露";
                    is = true;
                } else if (t == solartime[15]) {
                    holiday = "秋分";
                    is = true;
                }
                break;
            case 10:
                if (t == solartime[16]) {
                    holiday = "寒露";
                    is = true;
                } else if (t == solartime[17]) {
                    holiday = "霜降";
                    is = true;
                }
                break;
            case 11:
                if (t == solartime[18]) {
                    holiday = "立冬";
                    is = true;
                } else if (t == solartime[19]) {
                    holiday = "小雪";
                    is = true;
                }
                break;
            case 12:
                if (t == solartime[20]) {
                    holiday = "大雪";
                    is = true;
                } else if (t == solartime[21]) {
                    holiday = "冬至";
                    is = true;
                }
                break;
            case 1:
                if (t == solartime[22]) {
                    holiday = "小寒";
                    is = true;
                } else if (t == solartime[23]) {
                    holiday = "大寒";
                    is = true;
                }
                break;
        }
        switch (t) {
            case 101:
                holiday = "元旦";
                isRed = true;
                is = true;
                break;
            case 214:
                holiday = "情人节";
                is = true;
                break;
            case 308:
                holiday = "妇女节";
                is = true;
                break;
            case 312:
                holiday = "植树节";
                is = true;
                break;
            case 315:
                holiday = "消费日";
                is = true;
                break;
            case 401:
                holiday = "愚人节";
                is = true;
                break;
            // case 407:
            // holiday="卫生日";
            // is=true;
            // break;
            case 501:
                holiday = "劳动节";
                is = true;
                break;
            case 504:
                holiday = "青年节";
                is = true;
                break;
            // case 512:
            // holiday="护士节";
            // is=true;
            // break;
            // case 513:
            // holiday="助残日";
            // is=true;
            // break;

            case 601:
                holiday = "儿童节";
                is = true;
                break;
            case 605:
                holiday = "世界环境日";
                is = true;
                break;
            case 701:
                holiday = "建党节";
                is = true;
                break;
            case 801:
                holiday = "建军节";
                is = true;
                break;
            case 910:
                holiday = "教师节";
                is = true;
                break;
            case 1001:
                holiday = "国庆节";
                is = true;
                break;
            case 1225:
                holiday = "圣诞节";
                is = true;
                break;
            default:
                // is=false;
                break;
        }

        return is;
    }

    @SuppressWarnings("deprecation")
    public void GenView() {
        dataLinear.removeAllViews();
        mLayoutParamss.weight = 1;
        LayoutInflater lif = LayoutInflater.from(context);
        LinearLayout temp = new LinearLayout(context);
        int size = data.size();
        for (int i = 0; i < size; i++) {
            View convertView = lif.inflate(R.layout.gritem, null);
            TextView time = (TextView) convertView.findViewById(R.id.time);
            TextView lunar = (TextView) convertView.findViewById(R.id.lunar);
            TextView fraction = (TextView) convertView.findViewById(R.id.fraction);
            LinearLayout itemroot = (LinearLayout) convertView.findViewById(R.id.itemroot);
            HashMap<String, String> map = data.get(i);
            if ((i + 1) < size) {
                HashMap<String, String> map2 = data.get(i + 1);
                if (map2.get("lunar").equals("春节")) {
                    map.put("lunar", "除夕");
                }
            }
            if (map.get("isMonth").equals("1"))// 1是本月
            {
                itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                if (map.get("isToday").equals("1"))// 1是今天
                {
                    time.setTextColor(getResources().getColor(R.color.sunday_txt));
                    lunar.setTextColor(getResources().getColor(R.color.sunday_txt));
//                    itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity_jintian));
                } else {
                    itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                }
//                int m = (i + 1) % 7;
//                if (m == 1 || m == 0) {
//                    time.setTextColor(Color.rgb(50, 79, 133));
//                }
                if (map.get("isHoliday").equals("1")) // 节日
                {
                    time.setTextColor(Color.RED);
                }
                itemroot.setTag(R.id.calendar_index, "1");//0其他,1是本月
            } else {
                time.setTextColor(getResources().getColor(R.color.othermonth_txt));
                lunar.setTextColor(getResources().getColor(R.color.othermonth_txt));
                itemroot.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_riliactivity));
                itemroot.setTag(R.id.calendar_index, "0");
            }
            String day = map.get("day");
            String datestr = standard_year + "-" +
                    (standard_month > 9 ? standard_month : "0" + standard_month) + "-" +
                    (day.length() > 1 ? day : "0" + day);
            if (map.get("isMonth").equals("1")) {// 1是本月
                if (App.getDBcApplication().queryISNOTHOLIDAY(datestr).equals("1")) {//休息
                fraction.setText("休");
                fraction.setTextColor(getResources().getColor(R.color.sunday_txt));
            } else if (App.getDBcApplication().queryISNOTHOLIDAY(datestr).equals("2")) {//上班
                fraction.setText("班");
                fraction.setTextColor(getResources().getColor(R.color.title0));
            } else {
                fraction.setVisibility(View.GONE);
            }}
            if (!map.get("isMonth").equals("1")) {
                time.setVisibility(View.GONE);
                fraction.setVisibility(View.GONE);
                lunar.setVisibility(View.GONE);
            }
            time.setText(day);
            lunar.setText(map.get("lunar"));
            itemroot.setTag(day);
            itemroot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String day = v.getTag().toString();
                    // 0其他,1是本月
                    String calendar_index = v.getTag(R.id.calendar_index).toString();
                    if ("1".equals(calendar_index)) {
                        Intent intent = null;
                        String dateTime = Integer.toString(standard_year)
                                + "-"
                                + (standard_month > 9 ? "" + standard_month
                                : "0" + standard_month) + "-"
                                + (Integer.parseInt(day) > 9 ? day : "0" + day);
                        Message message = new Message();
                        message.what = 9;
                        message.obj = dateTime;
                        handlerrili.sendMessage(message);
                    }
                }
            });
            if ((i + 1) % 7 != 0) {
                temp.addView(convertView, mLayoutParamss);
            } else {
                if (i != 0) {
                    temp.addView(convertView, mLayoutParamss);
                    dataLinear.addView(temp, mLayoutParamss);
                    temp = new LinearLayout(context);
                }
            }
        }
    }

    /*
     * 基姆拉尔森计算公式 QgW4jIbx W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7 /
     *
     * d 天 m 月 y 年 1月2月换算为去年的13 14月计算
     *
     * 基姆拉尔森计算公式的C#的实现 %NfbgJcL_ //y：年，m：月，d：日。在参数都只传入相应的整数
     */
    private int calWeek(int y, int m, int d) {
        int a = 7; // 用来保存计算得到的星期几的整数 Dz>v;%$S-
        if ((m == 1) || (m == 2))// 如果是一月或二月进行换算 uWKc .
        {
            m += 12;
            y--;
        }
        a = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; // 得到的星期几的整数
        // 
        // 7ehs+GI
        a++;
        if (a == 7) {
            a = 0;
        }
        return a;
    }

    public void calLeapYear(int i) {
        if (i % 100 == 0) {
            if (i % 400 == 0) {
                isLeap = true;
            } else {
                isLeap = false;
            }
        } else {
            if (i % 4 == 0) {
                isLeap = true;
            } else {
                isLeap = false;
            }
        }
    }

}
